// pages/server_end/server_ends/server_ends.js
const app = getApp();
const request = require('../../../utils/request.js');
const url = require('../../../utils/url.js');
const cookie = require('../../../utils/cookie.js');
import Wxml2Canvas from 'wxml2canvas'; 
Page({
     
    /**
     * 页面的初始数据
     */
    data: {
        imgs: [],
        picList: [],
		picLists:[],
        imgss: [],
		 order:'',
        show1:false,
        imgUrl:'',
		addr:'',
 setlocation: 0,
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
		this.setData({
		   id:options.id
		})
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {



    },
	makeCall(e){
		   var phone = e.currentTarget.dataset.phone;
		      wx.makePhoneCall({
		        phoneNumber: phone,
		        success: function() {
		          console.log('Call Success');
		        },
		        fail: function() {
		          console.log('Call Fail');
		        }
		      });
	},
    drawMyCanvas() {
      wx.showLoading()
      const that = this
      const query = wx.createSelectorQuery().in(this);
      query.select('#my-canvas').fields({ // 选择需要生成canvas的范围
          size: true,
          scrollOffset: true
      }, data => {
          let width = data.width;
          let height = data.height;
          that.setData({
              width,
              height
          })
          setTimeout(() => {
              console.log('地方画图');
              that.startDraw()
          }, 1500);
     }).exec()
},
startDraw() {
      let that = this
      
      // 创建wxml2canvas对象
      let drawMyImage = new Wxml2Canvas({
        element: 'myCanvas', // canvas的id,
        obj: that, // 传入当前组件的this
        width: that.data.width * 2,
        height: that.data.height * 2,
        background: '#141415', // 生成图片的背景色
        progress(percent) { // 进度
          // console.log(percent);
        },
        finish(url) { // 生成的图片
          wx.hideLoading()
          that.savePoster(url)
        },
        error(res) { // 失败原因
          console.log(res);
          wx.hideLoading()
        }
      }, this);
      let data = {
          // 获取wxml数据
          list: [{
              type: 'wxml',
              class: '.my_canvas .my_draw_canvas',  // my_canvas要绘制的wxml元素根类名， my_draw_canvas单个元素的类名（所有要绘制的单个元素都要添加该类名）
              limit: '.my_canvas', // 要绘制的wxml元素根类名
              x: 0,
              y: 0
          }]
      }
      // 绘制canvas
      drawMyImage.draw(data, this);
  },
savePoster() {
      const that = this
      wx.saveImageToPhotosAlbum({
          filePath: that.data.imgUrl,
          success: function() {
              wx.showToast({
                  title: '保存成功',
                  icon: 'none',
                  duration: 1500
              });
          },
          fail(err) {
            if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
              wx.showModal({
                title: '提示',
                content: '需要您授权保存相册',
                showCancel: false,
                success: modalSuccess => {
                  wx.openSetting({
                    success(settingdata) {
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                          wx.saveImageToPhotosAlbum({
                              filePath: that.data.imgUrl,
                              success: function () {
                                wx.showToast({
                                  title: '保存成功',
                                  icon: 'success',
                                  duration: 2000
                                })
                              },
                          })
                      } else {
                          wx.showToast({
                              title: '授权失败，请稍后重新获取',
                              icon: 'none',
                              duration: 1500
                          });
                      }
                    }
                  })
                }
              })
            }
          }
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        var that = this;
        cookie.getCookie('userInfo', function (res) {
            if (res) {
                var etime = Date.parse(new Date()) / 1000;

                if (etime < res.expiretime) {
                    that.setData({
                        login: 1,
                        token: res.token
                    })
                }
				 that.getOrder();
            }
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    changeAgreement(){
        this.setData({
            agreement:false
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },




    showtag() {
        this.setData({
            show1: true
        })
    },
    closeTime() {
        this.setData({
            show1: false
        })
    },
    open1() {
        this.setData({
            show2: true
        })
    },
	makecall(e) {
	  var phone = e.currentTarget.dataset.phone;
	  wx.makePhoneCall({
	    phoneNumber: phone,
	  })
	},
	getOrder:function(){
	  var that = this;
	  let param = {
	    scoure: 'wxapp',
	    token:that.data.token,
	    id:that.data.id
	  }
	  wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
	  request.request(url.workerorderdetail, param, url.REQUEST_METHOD_GET).then((res) => {
	    wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
	    //console.log(res.data.data);
	    if(res.data.code==1){
	       that.setData({
	          order:res.data.data,
	       })
	     }
	  })
	},
	apply(that) {
		wx.requestSubscribeMessage({
					    tmplIds: [
				      'b_XBUUhR-JJVTL-aJBDk8nUcECOyhEnSxYI4s57cOvo'
					    ],
					    success: (res) => {
					    },
					    fail: (res) => {
					    },
					  })
		var that = this;
	    if (that.data.addr =='') {
	        wx.showToast({
	            title: '请设置当前地址',
	            icon: 'none'
	        })
	        return false;
	    }
	    let param = {
	        scoure: 'wxapp',
	        token: that.data.token,
	        check_images: that.data.picList,
			order_id:that.data.order.id,
			order_status:40,
			arrive_address: that.data.addr

	    }
	
	    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
	    request.request(url.updateordercheckimages, param, url.REQUEST_METHOD_POST).then((res) => {
	        wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
	        wx.showToast({
	            title: res.data.msg,
	            icon: "none"
	        });

	        if (res.data.code == 1) {
	            wx.showToast({
	                title: '提交成功',
	                icon: 'success'
	              })

	              setTimeout(function () {
	               wx.navigateTo({
	                 url: '/pages/server_end/index/index'
	               })
	            }, 1500)
	          } else {
	            wx.showToast({
	              title: res.data.msg,
	              icon: 'none',
	              duration: 2000
	            })
	          }
	        })



	},
    closeTime2() {
        this.setData({
            show1: false,
            show2: false
        })
    },
    choseTag(e) {
        var that = this;
        var id = e.currentTarget.dataset.id;
        that.data.servicetaglist.forEach((item, index) => {
            console.log(item.id);
            if (item.id == id) {
                if (item.active == 1) {
                    var active = 0;
                } else {
                    var active = 1;
                }
                var sItem = 'servicetaglist[' + index + '].active';
                this.setData({
                    [sItem]: active
                })
            }
        });
        var array = [];
        var arrayIds = [];
        that.data.servicetaglist.forEach((item, index) => {
            if (item.active == 1) {
                array.push(that.data.servicetaglist[index]);
                arrayIds.push(that.data.servicetaglist[index].id);
            }
        })
        that.setData({
            taglist: array,
            tagIds: arrayIds
        })
    },
    ChangeUpImagesBtn(){
      this.setData({
        show1:false
      })
    },
    regionChange(e) {
        console.log('picker发送选择改变，携带值为', e.detail)
        this.setData({
            postcode: e.detail.postcode,
            regionValue: e.detail.value
        })
    },
    choselocation() {
        var that = this;
        console.log('wxchoseLocation');
        wx.chooseLocation({
            success: function (res) {
                console.log("地图点击事件：" + JSON.stringify(res));
                that.setData({
                    addr: res.address,
                    lat: res.latitude,
                    lng: res.longitude,
                    setlocation: 1
                });

            }
        })
    },
    // 删除图片
    deleteImg: function (e) {
        var imgs = this.data.imgs;
        var picList = this.data.picList;
        var index = e.currentTarget.dataset.index;
        imgs.splice(index, 1);
        picList.splice(index, 1);
        this.setData({
            imgs: imgs,
            picList: picList
        });
    },
    chooseImg: function (e) {
        var that = this;
        var imgs = this.data.imgs;
        if (imgs.length >= 3) {
            this.setData({
                lenMore: 1
            });
            setTimeout(function () {
                that.setData({
                    lenMore: 0
                });
            }, 2500);
            return false;
        }
        

        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                if (res.errMsg == "chooseImage:ok") {


                    wx.showLoading({ //显示loding提示框
                        title: '正在上传中...',
                    })
                    let picList = that.data.picList
                    var imgs = that.data.imgs;
                    var currentDate = new Date();
                    var currentTime = currentDate.toLocaleString();
                    res.tempFilePaths.forEach((item, index) => {
                        imgs.push(item)
                        that.setData({
                            imgs: imgs,
                        });
                        wx.uploadFile({
                            url: url.HttpServerHostAddress + url.uploadpic,
                            filePath: item,
                            name: 'file',
                            formData: {
                                token: that.data.token,
                                water_text: currentTime +'|' + that.data.order.addr
                            },
                            success: function (res) {
                                let ress = JSON.parse(res.data)
                                if (ress.code == 1) {
                                    var picList = that.data.picList;
                                    picList.push(JSON.parse(res.data).data.url);
                                    that.setData({
                                        picList: picList,
                                    })
                                    console.log(picList);
                                } else {
                                    wx.showToast({
                                        title: JSON.parse(res.data).msg,
                                        icon: 'none',
                                        duration: 3000
                                    })
                                    return;
                                }
                            },
                            fail: res => {
                                console.log(res)
                            }
                        })
                    })
                    wx.hideLoading(); //隐藏loading提示框
                }
            }
        });
    },

    deleteImgs: function (e) {
        var imgs = this.data.imgss;
        var picList = this.data.picLists;
        var index = e.currentTarget.dataset.index;
        imgs.splice(index, 1);
        picList.splice(index, 1);
        this.setData({
            imgss: imgs,
            picLists: picList
        });
        console.log(picList);
    },
    chooseImgs: function (e) {
        var that = this;
        var imgs = this.data.imgss;
        if (imgs.length >= 4) {
            this.setData({
                lenMore: 1
            });
            setTimeout(function () {
                that.setData({
                    lenMore: 0
                });
            }, 2500);
            return false;
        }
        var count = 4 - imgs.length;
        if (count < 1) {
            return false;
        }

        wx.chooseImage({
            count: count, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                if (res.errMsg == "chooseImage:ok") {
                    wx.showLoading({ //显示loding提示框
                        title: '正在上传中...',
                    })
                    let picList = that.data.picLists
                    var imgs = that.data.imgss;
                    res.tempFilePaths.forEach((item, index) => {
                        imgs.push(item)
                        that.setData({
                            imgss: imgs,
                        });
                        wx.uploadFile({
                            url: url.HttpServerHostAddress + url.uploadpic,
                            filePath: item,
                            name: 'file',
                            formData: {
                                token: that.data.token
                            },
                            success: function (res) {
                                let ress = JSON.parse(res.data)
                                if (ress.code == 1) {
                                    var picList = that.data.picLists;
                                    picList.push(JSON.parse(res.data).data.url);
                                    that.setData({
                                        picLists: picList,
                                    })
                                    console.log(picList);
                                } else {
                                    wx.showToast({
                                        title: JSON.parse(res.data).msg,
                                        icon: 'none',
                                        duration: 3000
                                    })
                                    return;
                                }
                            },
                            fail: res => {
                                console.log(res)
                            }
                        })
                    })
                    wx.hideLoading(); //隐藏loading提示框
                }
            }
        });
    },
    uploadidcardImage(e) {
        var type = e.currentTarget.dataset.type;
        var that = this;
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                if (res.errMsg == "chooseImage:ok") {
                    wx.showLoading({ //显示loding提示框
                        title: '正在上传中...',
                    })
                    res.tempFilePaths.forEach((item, index) => {

                        wx.uploadFile({
                            url: url.HttpServerHostAddress + url.uploadpic,
                            filePath: item,
                            name: 'file',
                            formData: {
                                token: that.data.token
                            },
                            success: function (res) {
                                let ress = JSON.parse(res.data)
                                if (ress.code == 1) {
                                    if (type == 1) {
                                        that.setData({
                                            uploadfront: 1,
                                            idcard_front_image: JSON.parse(res.data).data.url,
                                            idcard_front_image_url: JSON.parse(res.data).data.fullurl
                                        })
                                    } else {
                                        that.setData({
                                            uploadback: 1,
                                            idcard_back_image: JSON.parse(res.data).data.url,
                                            idcard_back_image_url: JSON.parse(res.data).data.fullurl
                                        })
                                    }
                                } else {
                                    wx.showToast({
                                        title: JSON.parse(res.data).msg,
                                        icon: 'none',
                                        duration: 3000
                                    })
                                    return;
                                }
                            },
                            fail: res => {
                                console.log(res)
                            }
                        })
                    })
                    wx.hideLoading(); //隐藏loading提示框
                }
            }
        });
        wx.chooseImages({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                if (res.errMsg == "chooseImage:ok") {
                    wx.showLoading({ //显示loding提示框
                        title: '正在上传中...',
                    })
                    res.tempFilePaths.forEach((item, index) => {

                        wx.uploadFile({
                            url: url.HttpServerHostAddress + url.uploadpic,
                            filePath: item,
                            name: 'file',
                            formData: {
                                token: that.data.token
                            },
                            success: function (res) {
                                let ress = JSON.parse(res.data)
                                if (ress.code == 1) {
                                    if (type == 1) {
                                        that.setData({
                                            uploadfront: 1,
                                            idcard_front_image: JSON.parse(res.data).data.url,
                                            idcard_front_image_url: JSON.parse(res.data).data.fullurl
                                        })
                                    } else {
                                        that.setData({
                                            uploadback: 1,
                                            idcard_back_image: JSON.parse(res.data).data.url,
                                            idcard_back_image_url: JSON.parse(res.data).data.fullurl
                                        })
                                    }
                                } else {
                                    wx.showToast({
                                        title: JSON.parse(res.data).msg,
                                        icon: 'none',
                                        duration: 3000
                                    })
                                    return;
                                }
                            },
                            fail: res => {
                                console.log(res)
                            }
                        })
                    })
                    wx.hideLoading(); //隐藏loading提示框
                }
            }
        });

    },
})
